package com.zhangdi.dwperms.realm;

import com.zhangdi.dwperms.bo.ShiroAccount;
import com.zhangdi.dwperms.commons.security.Encoder;
import com.zhangdi.dwperms.entity.Account;
import com.zhangdi.dwperms.token.AuthToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.util.ByteSource;

public class NormalRealm extends BaseRealm {

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        AuthToken token = (AuthToken) authenticationToken;
        //根据账号查询信息
        Account account = accountDao.findByUsername((String) token.getPrincipal());
        if (account == null) {
            throw new UnknownAccountException();
        }

        ShiroAccount shiroAccount = new ShiroAccount();
        shiroAccount.setUsername(account.getUsername());
        shiroAccount.setUserId(account.getUser().getId());

        return new SimpleAuthenticationInfo(shiroAccount, account.getPassword(),
                ByteSource.Util.bytes(Encoder.decode(account.getSalt())), getName());
    }
}
